import { closeDB, getDB } from "@/utils/db";
import { newId } from "@/utils/id";
import { err, ok } from "@/utils/resp";

export async function GET() {
  try {
    const db = await getDB();
    let sub: Sub | undefined = await db.get(
      "SELECT id FROM subs ORDER BY id DESC LIMIT 1"
    );
    if (!sub) {
      const id = newId();
      await db.run("INSERT INTO subs(id) VALUES (?)", id);
      sub = { id };
    }
    await closeDB();
    return ok(sub);
  } catch (e) {
    return err(e as Error);
  }
}
export async function POST() {
  try {
    const db = await getDB();
    const id = newId();
    await db.run("INSERT INTO subs(id) VALUES (?)", id);
    await closeDB();
    return ok({ id });
  } catch (e) {
    return err(e as Error);
  }
}
export async function DELETE() {
  try {
    const db = await getDB();
    const r = await db.run("DELETE FROM subs");
    await closeDB();
    return ok({ aff: r.changes });
  } catch (e) {
    return err(e as Error);
  }
}
